package com.wwwarehouse.usercenter.fragment.business_relationship;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.adapter.SelectPermissionPagerAdapter;
import com.wwwarehouse.usercenter.bean.business_relationship.BRCFDTagsBean;
import com.wwwarehouse.usercenter.bean.business_relationship.BRCustomerFileDetailBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.wwwarehouse.usercenter.eventbus_event.BREvent;
import com.wwwarehouse.usercenter.eventbus_event.BRTagsEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


/**
 * @author : mundane
 * @time : 2017/9/19 20:35
 * @description :
 * @file : BRCFDTagsFragment.java
 */

public class BRCFDTagsFragment extends BaseFragment implements BRCFDTagsListFragment.OnButtonClickedListener {

    private CustomViewPagerInternal mCustomViewPagerInternal;
    private CirclePageIndicator mCirclePagerIndicator;
    private List<Fragment> mFragmentList;
    private SelectPermissionPagerAdapter mViewPagerAdapter;
    private ElasticScrollView mElasticScrollView;
    private List<FilterBean> mFilterList;
    private Button mBtnDistribute;
    private BRCFDTagsBean bean;

    private String tagBusinessUkid;
    private ArrayList<BRCustomerFileDetailBean.TagsBean> tagIds;
    private ArrayList<BRCustomerFileDetailBean.TagsBean> newTagIds;


    private NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        mStateLayout.showContentView();
                        bean = JSON.parseObject(commonClass.getData().toString(), BRCFDTagsBean.class);

                        mFragmentList.clear();
                        int pages = bean.getTotal() / bean.getSize();
                        if (bean.getTotal() % bean.getSize() != 0)
                            pages++;
                        for (int i = 0; i < pages; i++) {
                            BRCFDTagsListFragment listFragment = BRCFDTagsListFragment.newInstance(i + 1, bean, tagBusinessUkid, tagIds,newTagIds);
                            listFragment.setOnButtonClickedListener(BRCFDTagsFragment.this);
                            mFragmentList.add(listFragment);
                        }
                        mCustomViewPagerInternal.removeAllViews();
                        mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                        mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
                        mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
                        refreshButtonState();

                    } else {
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };
    private StateLayout mStateLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            tagBusinessUkid = bundle.getString("tagBusinessUkid");
            tagIds = bundle.getParcelableArrayList("tags");
        }
        newTagIds = new ArrayList<>();
        for(BRCustomerFileDetailBean.TagsBean tagsBean : tagIds){
            BRCustomerFileDetailBean.TagsBean tagsBean1 = new BRCustomerFileDetailBean().new TagsBean();
            tagsBean1.setTagId(tagsBean.getTagId());
            tagsBean1.setTagName(tagsBean.getTagName());
            newTagIds.add(tagsBean1);
        }
        mFragmentList = new ArrayList<>();
        mFilterList = new ArrayList<>();
//        mSelectedDataList = new ArrayList<>();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pager_distribute_authority, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // findViewById
        mCustomViewPagerInternal = $(R.id.cvpi);
        mCirclePagerIndicator = $(R.id.cpi);
        mElasticScrollView = $(R.id.esv);
        mBtnDistribute = $(R.id.btn_distribute);
        mStateLayout = $(R.id.slt);
        mStateLayout.showProgressView(true);
        mBtnDistribute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 确定按钮
                 */
                BREvent event = new BREvent(BREvent.TAGS);
                event.setTagsBeenList(newTagIds);
                EventBus.getDefault().post(event);
                popFragment();
            }
        });
        mBtnDistribute.setText(getString(R.string.user_sure));
        cardDeskOption();
    }

    private boolean isShowBtn = false;

    private void cardDeskOption() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                isShowBtn = !isShowBtn;
                if (isShowBtn) {
                    ((BaseCardDeskActivity) mActivity).showTitleBt1();
                    ((BaseCardDeskActivity) mActivity).showTitleBt2();
                    ((BaseCardDeskActivity) mActivity).setTitleBt1Text(getString(R.string.user_br_update_tags));
                    ((BaseCardDeskActivity) mActivity).setTitleBt2Text(getString(R.string.user_br_add_tags));
                    ((BaseCardDeskActivity) mActivity).downPull_3();
                } else {
                    ((BaseCardDeskActivity) mActivity).downPull_3();
                }
            }

            @Override
            public void onUpPull() {

            }
        });

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof BRCFDTagsFragment) {
            if (newTagIds.size() > 0) {
                mActivity.setTitle(String.format(getString(R.string.user_br_select_tags) + "(%d)", newTagIds.size()));
            } else {
                mActivity.setTitle(getString(R.string.user_br_select_tags));
            }
        }
    }

    @Override
    public void requestDatas() {
        searchCmTagByBusinessUkid(1);
    }

    /**
     * 查找业务单位所属标签及预设标签
     *
     * @param page 第几页
     */
    private void searchCmTagByBusinessUkid(int page) {
        Map<String, Object> map = new HashMap<>();
        map.put("tagType", "BU_REL_CUS");
        map.put("tagBusinessUkid", tagBusinessUkid);
        map.put("page", page);
        map.put("size", 27);
        NoHttpUtils.httpPost(UserCenterConstant.SEARCH_CMTAG_BY_BUSINESS_UKID, map, onResponseListener, 0);
    }

    @Override
    public void onButtonClicked() {
        refreshButtonState();
    }

    private void refreshButtonState() {
//        mSelectedDataList.clear();
//        for (ArrayList<AuthorityWrapItemBean> list : mFragmentDataList) {
//            for (AuthorityWrapItemBean wrapItemBean : list) {
//                if (wrapItemBean.isSelected) {
//                    mSelectedDataList.add(wrapItemBean.mItemBean);
//                }
//            }
//        }
        if (newTagIds.size() > 0) {
            mActivity.setTitle(String.format(getString(R.string.user_br_select_tags) + "(%d)", newTagIds.size()));
        } else {
            mActivity.setTitle(getString(R.string.user_br_select_tags));
        }
        mBtnDistribute.setVisibility(newTagIds.size() > 0 ? View.VISIBLE : View.INVISIBLE);
    }

    /**
     * 修改标签
     */
    @Override
    public void titleBt1Click() {
        if (peekFragment() instanceof BRCFDTagsFragment) {
            BRCFDTagsUpdateFragment brcfdTagsUpdateFragment = new BRCFDTagsUpdateFragment();
            Bundle bundle = new Bundle();
            bundle.putString("tagBusinessUkid", tagBusinessUkid);
            bundle.putParcelableArrayList("tagIds", tagIds);
            brcfdTagsUpdateFragment.setArguments(bundle);
            pushFragment(brcfdTagsUpdateFragment);
        }
    }

    /**
     * 新增标签
     */
    @Override
    public void titleBt2Click() {
        if (peekFragment() instanceof BRCFDTagsFragment) {
            BRAddTagsFragment brAddTagsFragment = new BRAddTagsFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("from", BRAddTagsFragment.FROM_ADD);
            bundle.putString("tagBusinessUkid", tagBusinessUkid);
            bundle.putString("tagParentUkid", null);
            bundle.putString("tagType","BU_REL_CUS");
            brAddTagsFragment.setArguments(bundle);
            pushFragment(brAddTagsFragment);
        }
    }

    public void onEventMainThread(BRTagsEvent event) {
        String msg = event.getMsg();
        if ("BRCFDTagsFragment".equals(msg)) {
            searchCmTagByBusinessUkid(1);
        }
    }
}
